<template>
  <div class="rental-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>租赁记录管理</span>
        </div>
      </template>

      <el-table :data="rentalList" style="width: 100%" class="rental-table">
        <el-table-column prop="id" label="租赁ID" min-width="80" align="center" />
        <el-table-column prop="customerName" label="客户姓名" min-width="100" show-overflow-tooltip />
        <el-table-column prop="carInfo" label="车辆信息" min-width="180" show-overflow-tooltip />
        <el-table-column prop="startRentalTime" label="开始日期" min-width="120" align="center" />
        <el-table-column prop="endRentalTime" label="结束日期" min-width="120" align="center" />
        <el-table-column prop="realReturnTime" label="实际归还日期" min-width="120" align="center">
          <template #default="scope">
            {{ scope.row.realReturnTime || '未归还' }}
          </template>
        </el-table-column>
        <el-table-column prop="money" label="总金额" min-width="100" align="center">
          <template #default="scope">
            <span class="money-text">¥{{ scope.row.money }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row)" size="small">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑租赁"
      width="500px"
    >
      <el-form :model="rentalForm" label-width="100px" :rules="rules" ref="rentalFormRef">
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="rentalForm.customerName" placeholder="请输入客户姓名" disabled />
        </el-form-item>
        <el-form-item label="车辆信息" prop="carInfo">
          <el-input v-model="rentalForm.carInfo" placeholder="请输入车辆信息" disabled />
        </el-form-item>
        <el-form-item label="开始日期" prop="startRentalTime">
          <el-date-picker
            v-model="rentalForm.startRentalTime"
            type="date"
            placeholder="选择开始日期"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endRentalTime">
          <el-date-picker
            v-model="rentalForm.endRentalTime"
            type="date"
            placeholder="选择结束日期"
          />
        </el-form-item>
        <el-form-item label="实际归还日期" prop="realReturnTime">
          <el-date-picker
            v-model="rentalForm.realReturnTime"
            type="date"
            placeholder="选择实际归还日期"
          />
        </el-form-item>
        <el-form-item label="总金额" prop="money">
          <el-input-number v-model="rentalForm.money" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="rentalForm.status" placeholder="请选择状态">
            <el-option label="已拒绝" :value="-1" />
            <el-option label="待审核" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const rentalList = ref([])

// 获取租赁记录列表
const fetchRentalList = async () => {
  console.log('开始获取租赁记录列表...')
  try {
    const token = localStorage.getItem('Token')
    const response = await fetch(`http://localhost:8080/rental/list?page=${currentPage.value}&size=${pageSize.value}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      // token 过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('获取租赁记录列表成功，原始数据：', result)
    
    if (result.code === 200) {
      rentalList.value = result.data.records || []
      total.value = result.data.total || 0
      currentPage.value = result.data.current || 1
      pageSize.value = result.data.size || 10
      console.log('处理后的租赁记录列表数据：', rentalList.value)
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取租赁记录列表失败：', error)
    ElMessage.error('获取租赁记录列表失败：' + error.message)
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRentalList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchRentalList()
}

// 在组件挂载时获取租赁记录列表
onMounted(() => {
  console.log('组件已挂载，准备获取租赁记录列表')
  fetchRentalList()
})

const customerOptions = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' }
])

const carOptions = ref([
  { id: 1, plateNumber: '京A12345' },
  { id: 2, plateNumber: '京B67890' }
])

const dialogVisible = ref(false)
const dialogType = ref('edit')
const rentalFormRef = ref(null)
const rentalForm = reactive({
  id: null,
  customerName: '',
  carInfo: '',
  startRentalTime: '',
  endRentalTime: '',
  realReturnTime: '',
  money: 0,
  status: 1
})

const rules = {
  startRentalTime: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endRentalTime: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  money: [{ required: true, message: '请输入总金额', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 创建一个新对象，避免直接修改原始数据
  const formData = {
    id: row.id,
    customerName: row.customerName,
    carInfo: row.carInfo,
    startRentalTime: row.startRentalTime,
    endRentalTime: row.endRentalTime,
    realReturnTime: row.realReturnTime,
    money: row.money,
    status: Number(row.status)
  }
  Object.assign(rentalForm, formData)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该租赁记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const token = localStorage.getItem('Token')
      const response = await fetch(`http://localhost:8080/rental/delete/${row.id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Token': token
        }
      })

      if (response.status === 401) {
        // token 过期或无效，清除本地存储并跳转到登录页
        localStorage.removeItem('Token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('删除成功')
        // 刷新列表
        fetchRentalList()
      } else {
        throw new Error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败：', error)
      ElMessage.error('删除失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消删除操作
    ElMessage.info('已取消删除')
  })
}

const handleSubmit = async () => {
  if (!rentalFormRef.value) return
  
  await rentalFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('Token')
        const url = 'http://localhost:8080/rental/update'
        
        // 构造请求数据
        const requestData = {
          id: rentalForm.id,
          customerName: rentalForm.customerName,
          carInfo: rentalForm.carInfo,
          startRentalTime: rentalForm.startRentalTime,
          endRentalTime: rentalForm.endRentalTime,
          realReturnTime: rentalForm.realReturnTime,
          money: rentalForm.money,
          status: rentalForm.status
        }
        
        const response = await fetch(url, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          },
          body: JSON.stringify(requestData)
        })

        if (response.status === 401) {
          // token 过期或无效，清除本地存储并跳转到登录页
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success('修改成功')
          dialogVisible.value = false
          // 刷新列表
          fetchRentalList()
        } else {
          throw new Error(result.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败：', error)
        ElMessage.error('操作失败：' + error.message)
      }
    }
  })
}

// 获取状态类型
const getStatusType = (row) => {
  // 如果status=1并且realReturnTime不为null，则显示为维修中
  if (row.status == 1 && row.realReturnTime) {
    return 'warning'  // 维修中用橙色
  }

  const statusTypeMap = {
    '-1': 'danger',   // 已拒绝
    0: 'warning',     // 待审核
    1: 'primary',     // 进行中
    2: 'success'      // 已完成
  }
  return statusTypeMap[row.status] || 'info'
}

// 获取状态文本
const getStatusText = (row) => {
  // 如果status=1并且realReturnTime不为null，则显示为维修中
  if (row.status == 1 && row.realReturnTime) {
    return '维修中'
  }

  const statusMap = {
    '-1': '已拒绝',
    0: '待审核',
    1: '进行中',
    2: '已完成'
  }
  return statusMap[row.status] || '未知'
}
</script>

<style scoped>
.rental-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式优化 */
.rental-table {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.rental-table .el-table__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.rental-table .el-table__header th {
  background: transparent !important;
  color: white !important;
  font-weight: 600;
  border: none !important;
}

.rental-table .el-table__row {
  transition: all 0.2s ease;
}

.rental-table .el-table__row:hover {
  background-color: rgba(102, 126, 234, 0.05) !important;
}

.rental-table .el-table__cell {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 8px;
}

.money-text {
  font-weight: 600;
  color: #e6a23c;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.pagination-container .el-pagination {
  background: rgba(102, 126, 234, 0.05);
  padding: 15px 20px;
  border-radius: 25px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .rental-table {
    font-size: 13px;
  }

  .rental-table .el-table__cell {
    padding: 10px 6px;
  }
}

@media (max-width: 768px) {
  .rental-management {
    padding: 10px;
  }

  .rental-table {
    font-size: 12px;
  }

  .rental-table .el-table__cell {
    padding: 8px 4px;
  }

  .rental-table .el-button {
    padding: 4px 8px;
    font-size: 12px;
  }
}
</style>